<?php
namespace Admin\Model;
use Think\Model;
class CategoryModel extends Model{
	//允许接收的字段
	protected $insertFields = 'cat_name,parent_id,is_floor';
	//允许修改的字段
	protected $updateFields = 'id,cat_name,is_floor';
	//自动验证规则
	protected $_validate = array(
			array('cat_name', 'require', '分类Id不能为空', 1),
	);
	//打印树状图
	public function getTree(){
		$data = $this->select();
		return $this->_getTree($data);
	}
	/**
	 * $data  category 所有分类里面的数据  
	 * $parent_id    从第几极开始排序
	 * $level     顶级分类
	 */
	public function _getTree($data,$parent_id=0,$level=0){
		static $_ret = array(); // 保存排序好的结果的数组
		foreach ($data as $k => $v)
		{
			if($v['parent_id'] == $parent_id)
			{
				// 为这个分类添加一个level字段，标记这个分类是第几级的
				$v['level'] = $level;
				$_ret[] = $v;
				// 找这个$v的子分类
				$this->_getTree($data, $v['id'], $level+1);
			}
		}
		return $_ret;
	}
	//查找所有的子分类  //无限极递归
	public function getChildren($catId)
	{
		// 取出所有的分类
		$data = $this->select();
		// 先清空再递归找子分类
		return $this->_getChildren($data, $catId, TRUE);
	}
	protected function _getChildren($data, $parent_id, $isClear=FALSE)
	{
		static $_ret = array();  // 保存找到的子分类的ID
		// 如果是新的查询就清空,递归过程中不清空
		if($isClear)
			$_ret = array();  // 清空这个数组
		foreach ($data as $k => $v)
		{
			if($v['parent_id'] == $parent_id)
			{
				// 把这个子分类的ID放到数组中
				$_ret[] = $v['id'];
				// 再找这个分类的子分类
				$this->_getChildren($data, $v['id']);
			}
		}
		return $_ret;
	}
	
	//钩子函数
	public function  _before_delete($data,$option){
		//如果有子分类 则告诉不能删除
		$id = I('get.id');
		$data = $this->getChildren($id);
		if($data){
			$this->error = '有子分类不允许删除';
			return false;
			
		}
	}
	//分类模型中取出前三级的分类
	public function getNavData(){
		$all = $this->select();
		$ret = array();
			foreach ($all as $k=>$v){
				if($v['parent_id'] == 0){
					//再次跳出这个等级分类的子级
					foreach ($all as $k1=>$v1){
						if($v1['parent_id'] == $v['id']){
							//再次遍历
							foreach($all as $k2=>$v2){
								if($v2['parent_id'] == $v1['id']){
									$v1['children'][] = $v2;
								}
							
							}
							$v['children'][] = $v1;
						}
					}
					$ret[] = $v;
				}
				
			}
		return $ret;
	}
	//商品分类模型中封装一个方法  取得中间楼层里面的数据
	public function getFloorData(){
		//定义一个空数组
		
		$ret = array();
		$goodsModel = D('Admin/goods');
		$data = $this->select();
		foreach ($data as $k=>$v){
			if($v['parent_id'] == 0 && $v['is_floor'] == '是'){
				foreach ($data as $k1=>$v1){
				    if($v1['parent_id']==$v['id'] && $v1['is_floor']=='否'){
				    	//二级分类
				    	$v['subcategory'][] = $v1;
				    }
				    $i = 0;
				    if($v1['parent_id'] == $v['id'] && $v1['is_floor'] == '是' && $i<5){
				    	$v1['goods'] = $goodsModel->getGoodsByCatId($v1['id'],5);
				    	//var_dump($v1['goods']);die();
				    	$v['getcategory'][] = $v1;
				    	$i++;
				    }
				}
			 $ret[] = $v;
			}
		}
		return $ret;
		
	}
}